
showPage()

function showPage() {
  let id = localStorage.getItem('LISTDETAILSID')
  console.log(id)

  $.ajax({
    url: `https://xiongmaoyouxuan.com/api/detail?id=${id}`,
    type: 'get',
    success(res) {
      if (res.code === 200) {
        let data = res.data
        productMsg(data)
        sellerInfo(data)
        detailsOnload(data)
        setIndex(data.detail.photo)
        new Glass('.shop-pic')
        
      }
    }
  })
}

/**
 * 拿到数据，渲染展示区页面
 */
function productMsg(data) {
  for (var key in data) { // 总数据
    if (key === 'detail') { // 渲染页面需要的数据对象
      let listData = data[key]
      let pics = listData.photo
      let picStr = ''
      let priceStr = String(listData.price) // 价格只有一个数据，转成字符串处理
      let priceStrong = priceStr.slice(0, priceStr.indexOf('.')) // 第一个截取到 . 之前
      let digit = priceStr.slice(priceStr.indexOf('.')) // 从 . 截取到最后
      
      pics.forEach(pic => {
        picStr += `
          <div>
            <img src=${pic.url} alt="">
          </div>
        `
      })
      $('.zoom img').attr('src',`${pics[0].url}`)
      
      $('.pic-wrap').html(picStr)
      $('.pic-wrap img').first().addClass('ac')

      let msgStr = `
        <h1 class="shop-title">
          <div class="title-icon">
            <img src="../static/image/t-icon1.png" alt="">
            <img src="../static/image/t-icon2.png" alt="">
          </div>
          ${listData.title}
        </h1>

        <div class="shop-price">
          <p class="original-price">
            <i>原价￥${listData.originPrice}</i>
          </p>

          <div class="current-price">
            <span>券后价:</span>
            <span class="price"><i>￥</i>${priceStrong}<span class="digit">${digit}</span>
            </span>

            <span class="coupon-info">${listData.couponValue}</span>
            <span class="sale-num">${listData.saleNum}</span>
          </div>
        </div>
        <div class="last-tips">
          <p class="expire-date">
            <span>优惠有效期：${listData.expireDate}</span>
          </p>
         
          <button class="gobuy-btn">领券购买--购物车</button>
        </div>
      `
      $('.shop-msg').html(msgStr)
    }
  }
  addCrat(data)
}

/**
 * 卖家信息版块
 */
function sellerInfo(data) {
  let sellerMsg = data.shop

  let shopScoreText = sellerMsg.shopScoreText
  let desc = shopScoreText.slice(0, 2)
  let descInfo = shopScoreText.slice(2, 5)
  let serve = shopScoreText.slice(6, 8)
  let serveInfo = shopScoreText.slice(8, 11)
  let postSale = shopScoreText.slice(12, 14)
  let postSaleInfo = shopScoreText.slice(14, 17)



  $('.store-msg').html(
    `
      <div class="store-name">
      <img src="${sellerMsg.picUrl}" alt="">
      <h3>${sellerMsg.title}</h3>
    </div>

    <ul class="sotre-status">
      <li>
        <span>${desc}</span>
        <i>${descInfo}</i>
      </li>
      <li>
        <span>${serve}</span>
        <i>${serveInfo}</i>
      </li>
      <li>
        <span>${postSale}</span>
        <i>${postSaleInfo}</i>
      </li>
    </ul>
      `
  )
}

/**
* 商品详情描述渲染
*/

function detailsOnload(data) {
  var msg = data.detail.descContentList
  var str = ''
  msg.forEach(item => {

    str += `<img src="${item.image.url}" alt="">`
  })
  $('.imgs').html(str)
}




/**
 * 放大镜
 */

class Glass {
  constructor(selector) {
    this.showBox = document.querySelector(selector)
    this.picWrap = this.showBox.querySelector('.pic-wrap')
    this.list = this.picWrap.querySelectorAll('div')
    this.showImg = this.showBox.querySelector('img')
    this.mask = this.showBox.querySelector('.mask')
    this.bigImgBox = this.showBox.nextElementSibling
    this.bigImg = this.bigImgBox.querySelector('img')
    this.prev = this.showBox.querySelector('.swiper-button-prev')
    this.next = this.showBox.querySelector('.swiper-button-next')
    this.pagination = this.showBox.querySelector('.pagination')
    this.bindEvens()
  }

  /**
   * 事件绑定
   */
  bindEvens() {
    // 鼠标移入
    this.showBox.addEventListener('mouseover', () => {
      this.toggleEle('block')
      this.getScale()
    })
    // 鼠标移动
    this.showBox.addEventListener('mousemove', e => {
      e = e || window.event
      this.zoom(e)
    })
    // 鼠标移出
    this.showBox.addEventListener('mouseout', () => {
      this.toggleEle('none')
    })

  }

  /**
   * 显示隐藏
   */
  toggleEle(display) {
    this.mask.style.display = display
    this.bigImgBox.style.display = display
  }

  /**
   * 核心：移动放大
   */
  zoom(e) {
    // 设置遮罩层跟随鼠标，且鼠标出于遮罩层中心
    let left = e.offsetX - this.mask.offsetWidth / 2
    let top = e.offsetY - this.mask.offsetHeight / 2


    // 限定范围
    if (left < 0) left = 0
    if (top < 0) top = 0
    if (left > this.showBox.clientWidth - this.mask.offsetWidth) left = this.showBox.clientWidth - this.mask.offsetWidth
    if (top > this.showBox.clientHeight - this.mask.offsetHeight) top = this.showBox.clientHeight - this.mask.offsetHeight

    this.mask.style.left = left + 'px'
    this.mask.style.top = top + 'px'

    // 大图移动坐标计算 按比例 遮罩层尺寸:放大区域尺寸 = 遮罩层移动距离:大图移动距离

    let moveX = (left * this.bigImgBox.offsetWidth) / this.mask.offsetWidth
    let moveY = (top * this.bigImgBox.offsetHeight) / this.mask.offsetHeight


    // 方向移动，鼠标在展示区往右走，大图就要按比例往左走
    this.bigImg.style.left = -moveX + 'px'
    this.bigImg.style.top = -moveY + 'px'
  }
  /**
   * 动态计算大图宽高 根据比例 遮罩层尺寸:默认显示图片尺寸 = 发大镜区域尺寸:背景图片尺寸
   */
  getScale() {

    let bigPicWidth = (this.bigImgBox.offsetWidth * this.showBox.offsetWidth) / this.mask.offsetWidth
    let bigPicHeight = (this.bigImgBox.offsetHeight * this.showBox.offsetHeight) / this.mask.offsetHeight

    this.bigImg.style.width = bigPicWidth + 'px'
    this.bigImg.style.height = bigPicHeight + 'px'
  }

}
  /**
   * 创建分页器
   */
   function setIndex(picUrl) {

     // 根据渲染的图片创建分页器 -- li
     let imgList = document.querySelectorAll('.pic-wrap div img')
     let pagination = document.querySelector('.pagination')
    for (let i = 0; i < imgList.length; i++) {
      let li = document.createElement('li')
      li.innerHTML = i + 1
      document.querySelector('.pagination').appendChild(li)

    }
    // 点击换图
    var indexList = pagination.querySelectorAll('li') 
    var zoomImg = document.querySelector('.zoom img')
    for(let i = 0 ; i < indexList.length; i++){
      indexList[i].onclick = function () {
        console.log(imgList[i])
        for(var j = 0 ; j < indexList.length;j++){
          imgList[j].classList.remove('ac')
        }
        imgList[i].src = `${picUrl[i].url}`
        imgList[i].classList.add('ac')
        zoomImg.src = `${picUrl[i].url}`
      }
    }

  }

/**
 * 加入购物车
 * 在productMsg()里面调用
 */

function addCrat(data){
  let cart = document.querySelector('.gobuy-btn')

  cart.onclick = function(){
    console.log(data.detail)
    let shopName = data.detail.qunTitle
    let singlePrice = data.detail.price
    let id = data.detail.id

    // console.log(shopName,singlePrice,id)

    let cartMsg = JSON.parse(localStorage.getItem('MYCARTMSG')) || []
    console.log(cartMsg)

    let newMsg = {
      shopName: shopName,
      singlePrice: singlePrice,
      id: id,
      num: 1,
      state: false,
    
    }

    // 判断是否加入过购物车
    let isItem = cartMsg.find((item) =>  item.id == data.detail.id)
    
    if(isItem){
      isItem.num++
    }else{
      cartMsg.push(newMsg)
    }

    localStorage.setItem('MYCARTMSG',JSON.stringify(cartMsg))

    if(confirm('添加成功，立即前往购物车')) location.href = './cart.html'
    
  }
}





